<?php
namespace app\index\controller;

use think\View;
use think\Validate;
use think\Session;
use think\Controller;
use think\Db;
require_once APP_VENDOR.'Aliyunsms/api/Sms.php';


class Login extends Controller{

    //登录页
    public function index()
    {   
    	$view = new View();
        return $view->fetch();
    }
    //判断用户的登录状态
    public function isLogin(){
        $data['is_login'] = Session::has('user_mobile') ? 1 : 0; 
        return json($data);
    }

    //获取验证码
    public function getSms(){
        $mobile = input('mobile');

    	$data['verify'] = $this->getVerifity($mobile);
       
    	Session::set('verify',$data['verify']);

        return json($data);
    }

    private function getVerifity($mobile){
        $verify   = rand(1000,9999);
        $Sms = new \vendor\Aliyunsms\api\Sms("LTAIjwKoxUrL1xoS","y38qYYEKrClr0P8gTrpwAyUV55XtNR");
        $response = $Sms->sendSms(
            "力杆", // 短信签名
            "SMS_78900467", // 短信模板编号
            $mobile, // 短信接收者
            Array(  // 短信模板中字段的值
                "code"=>$verify,
                "product"=>"dsd"
            ),
            "123"
        );

        return $response->Code == 'OK' ? $verify : false; 
        
    }

    //用户登录
    public function doLogin(){
    	$user_info['mobile']      = input('mobile');
        
        if(!$result = Db::name('user')->where('mobile',$user_info['mobile'])->find()){
            $this->error('用户不存在,请先注册！');die;
        }

        $r_verify   = Session::get('verify'); //手机验证码
        $u_verify   = input('verify'); // 用户验证码

        
        if($r_verify != $u_verify ){
            $this->error('验证码不正确！');die;
        }
        
        $begintime = mktime(0,0,0,date('m'),date('d'),date('Y'));
        
        //判断今天是否已经赠送两次抽奖次数
        if($result['give_time'] < $begintime){

           $data['now_number'] = $result['now_number']+2;//每日登录添加2次抽奖次数
           $data['give_time']  = time();//赠送抽奖次数时间

           Db::name('user')->where('id',$result['id'])->update($data);
        }

        Session::set('user_mobile',$user_info['mobile']);
        
        $this->success('登录成功', 'Index/index');
 
    }

 
}
